package chpt11;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    public static void main(String[] args){
        try{
        	//服务器地址和端口号
        	String server_addr = "localhost";
        	int port = 9000;
            InetAddress host = InetAddress.getByName(server_addr);
            //创建客户端数据报Socket
            DatagramSocket client = new DatagramSocket();
            BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
            while(true){
            	System.out.print("Client:");
            	//从标准输入读取数据
                String line=in.readLine();
                byte[] data = line.getBytes("UTF-8");
                //创建发送数据的数据报
                DatagramPacket send_dp = new DatagramPacket(data,data.length,host,port);
                //发送数据报
                client.send(send_dp);
                if(line.equals("bye")){
                    break;
                }
                byte[] recvbuf = new byte[1024];
                //创建接收数据的数据报
                DatagramPacket recv_dp = new DatagramPacket(recvbuf,recvbuf.length);
                //接收数据报
                client.receive(recv_dp);
                //输出服务器返回的数据
                System.out.print("Server:");                
                System.out.println(new String(send_dp.getData(),0,send_dp.getLength(),"UTF-8"));
            }
            //关闭Socket
            client.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}